<template>
  <div>
    <projectinfo
      :parentInfoobj="parentInfoobj"
      :invoiceCompanyList="invoiceCompanyList"
      @update-info="handleInfoUpdate"
    ></projectinfo>
    <projectmedia
      :brandPlacementTypeList="brandPlacementTypeList"
      :medialist="medialist"
      @update-list="handleUpdateList"
      :parentInfoobj="parentInfoobj"
    ></projectmedia>
    
    <projectreport :parentInfoobj="parentInfoobj" :currentStageid="currentStageid"></projectreport>

    <div v-if="operationList.includes('order:add')">
      <el-divider></el-divider>
      <el-descriptions title="上传表单"></el-descriptions>
      <div class="upbtn">
        <el-button type="primary" @click="uploaddialog">上传表单</el-button>
      </div>
    </div>
   


    <el-dialog title="上传表单" :visible.sync="dialogVisible" width="70%">
      <el-form :model="form" :rules="rules" ref="form">
        <!-- <el-form-item
          label="订单类型"
          prop="fileType"
          label-width="100px"
          label-position="right"
        >
          <el-select v-model="form.fileType" placeholder="请选择订单类型">
            <el-option
              v-for="item in orderTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item
          label="文件"
          prop="fileMsg"
          label-width="100px"
          label-position="right"
        >
          <el-upload
            class="upload-demo"
            drag
            :action="url"
            :on-progress="uploadFileLoading"
            :data="{ token: $store.state.token, fileType: this.form.fileType }"
            :headers="{ 'Access-Control-Allow-Origin': '*' }"
            :show-file-list="false"
            :http-request="checkedFile"
            multiple
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item
          v-if="goodList && goodList.length > 0 && this.form.fileType == 1"
        >
          <div class="form_table_goods">
            <el-table
              :data="goodList"
              :summary-method="getSummaries"
              show-summary
              max-height="750"
              :row-style="{ height: '0' }"
              :cell-style="{ padding: '3px' }"
              style="width: 100%"
            >
              <el-table-column prop="goodName" fixed label="商品名称">
              </el-table-column>
              <el-table-column prop="goodSkuName" fixed label="商品规格">
              </el-table-column>
              <el-table-column prop="expirationDate" label="有效期至">
              </el-table-column>
              <el-table-column prop="warrantyDate" label="保质期">
              </el-table-column>
              <el-table-column prop="goodNum" label="数量"> </el-table-column>
              <el-table-column prop="goodPrice" label="旗舰店售卖价">
              </el-table-column>
              <el-table-column
                prop="goodOnlineLink"
                show-overflow-tooltip
                label="天猫/京东链接"
              >
              </el-table-column>
              <el-table-column prop="goodPic" label="图片">
                <template slot-scope="scope">
                  <el-image
                    v-if="scope.row.goodPic"
                    style="width: 100px; height: 100px"
                    :src="scope.row.goodPic"
                    :preview-src-list="[scope.row.goodPic]"
                  >
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="goodBoxNum" label="箱规（数量）">
              </el-table-column>
              <el-table-column prop="goodBoxNum" label="箱规（尺寸mm）">
              </el-table-column>
              <el-table-column prop="goodBoxSize" label="单个产品包装尺寸mm">
              </el-table-column>
              <el-table-column prop="shopFans" label="店铺粉丝量">
              </el-table-column>
              <el-table-column prop="goodSaleNum" label="产品销量">
              </el-table-column>
              <!-- <el-table-column
                        prop="finalPrice"
                        width="180"
                        label="旗舰店实际成交价">
                    </el-table-column> -->
              <el-table-column
                prop="realReadPrice"
                width="180"
                label="实际成交价"
              >
              </el-table-column>
              <el-table-column prop="totalPrice" fixed="right" label="货值合计">
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item
          v-if="goodList && goodList.length > 0 && this.form.fileType == 2"
        >
          <div class="form_table_goods">
            <el-table
              :data="goodList"
              :summary-method="getSummaries"
              show-summary
              max-height="750"
              :row-style="{ height: '0' }"
              :cell-style="{ padding: '3px' }"
              style="width: 100%"
            >
              <el-table-column prop="chainStoreName" fixed label="连锁店铺名称">
              </el-table-column>
              <el-table-column prop="category" fixed label="连锁店铺名称">
              </el-table-column>
              <el-table-column prop="storeNumber" label="店铺数量">
              </el-table-column>
              <el-table-column
                prop="averageScore"
                label="美团/大众点评店铺平均评分"
              >
              </el-table-column>
              <el-table-column prop="validityPeriod" label="有效期">
              </el-table-column>
              <el-table-column prop="distributedCities" label="分布城市">
              </el-table-column>
              <el-table-column prop="productName" label="产品名称">
              </el-table-column>
              <el-table-column prop="price" label="价值"> </el-table-column>
              <el-table-column prop="num" label="数量"> </el-table-column>
              <el-table-column prop="useRights" label="使用权益">
              </el-table-column>
              <el-table-column prop="couponForm" label="卡券形式">
              </el-table-column>
              <el-table-column prop="usageRestrictions" label="使用限制">
              </el-table-column>
              <el-table-column
                prop="storeLinks"
                show-overflow-tooltip
                label="店铺链接（美团、携程等）"
              >
              </el-table-column>
              <el-table-column prop="verificationProcess" label="核销流程">
              </el-table-column>
              <el-table-column prop="finalPrice" label="实际成交价">
              </el-table-column>
              <el-table-column prop="totalPrice" fixed="right" label="合计">
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item
          v-if="goodList && goodList.length > 0 && this.form.fileType == 3"
        >
          <div class="form_table_goods">
            <el-table
              :data="goodList"
              :summary-method="getSummaries"
              show-summary
              max-height="750"
              :row-style="{ height: '0' }"
              :cell-style="{ padding: '3px' }"
              style="width: 100%"
            >
              <el-table-column prop="hotelName" fixed label="酒店名称">
              </el-table-column>
              <el-table-column prop="hotelAddress" fixed label="酒店地址">
              </el-table-column>
              <el-table-column prop="busyTime" label="旺季时间">
              </el-table-column>
              <el-table-column prop="hotelType" label="房型"> </el-table-column>
              <el-table-column prop="expirationDate" label="有效期">
              </el-table-column>
              <el-table-column
                prop="isHaveMorning"
                label="是否含早"
              ></el-table-column>
              <el-table-column prop="num" label="数量"></el-table-column>
              <el-table-column prop="price" label="平台价"> </el-table-column>
              <el-table-column prop="url" show-overflow-tooltip label="链接">
              </el-table-column>
              <el-table-column prop="hotelPic" label="房间图片">
                <template slot-scope="scope">
                  <el-image
                    v-if="scope.row.hotelPic"
                    style="width: 100px; height: 100px"
                    :src="scope.row.hotelPic"
                    :preview-src-list="[scope.row.hotelPic]"
                  >
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间">
              </el-table-column>
              <el-table-column prop="realPrice" width="180" label="实际成交价">
              </el-table-column>
              <el-table-column prop="totalPrice" fixed="right" label="房值合计">
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>

   
  </div>
</template>

<script>
import APIOrder from "@/api/apiOrder";
import APIProjectFile from "@/api/apiProjectFile";
import APIProject from "@/api/apiProject";
import qs from "qs";
import API from "@/api/apidetail";
import APISysLabel from "@/api/apiSysLabel";
import projectinfo from "../create/ProjectInfo";
import projectmedia from "../create/ProjectMedia";
import projectreport from "../create/ProjectReport ";
import axios from "axios";
export default {
  components: {
    projectinfo,
    projectmedia,
    projectreport,
  },
  props:['currentStageid',"operationList"],
  data() {
    return {
      invoiceCompanyList:[],
      projectId: null,
      dialogVisible: false,
      parentInfoobj: {},
      brandPlacementTypeList: [],
      showStatus: true,
      medialist: {},
      pageNum: 1,
      pageSize: 10,
      uploadLoading: false,
      url: "",
      form: {
        fileType: 1,
        fileMsg: 1,
      },
      goodList: [],
      updateFileList: [],
      rules: {
        fileType: [
          { required: true, message: "请选择订单类型", trigger: "change" },
        ],

        // fileMsg: [
        //     { required: true, message: "请上传文件", trigger: "change" },
        // ],
      },
      orderTypeList: [
        {
          value: 1,
          label: "核价订单",
          departId: -1,
        },
        {
          value: 2,
          label: "本地生活",
          departId: 5032,
        }
      ],
    };
  },
  methods: {
    //基本信息
    getProjectManageMsg() {
      let params = {
        projectId: this.projectId,
        stageId:this.currentStageid
      };
      API.getProjectManageMsg(params).then((res) => {
        if (res.key == 1000) {
          this.parentInfoobj = res.result.data;
          if(this.parentInfoobj.invoiceCompany){
            this.parentInfoobj.invoiceCompany = Number(this.parentInfoobj.invoiceCompany)
          }
        }
      });
    },
    //投放品牌类型
    getSysLabelList() {
      const params = {
        token: this.$store.state.token,
        sysLabelIds: "2,18",
        stageId:this.currentStageid
      };
      APISysLabel.getSysLabelValueManageList(params).then((res) => {
        if (res.key == 1000) {
          this.brandPlacementTypeList = res.result.data[2];
          this.invoiceCompanyList = res.result.data[18];
        }
      });
    },
    handleUpdateList(data) {
      if (data) {
        this.pageNum = data.pageNum;
        this.pageSize = data.pageSize;
        this.keyword = data.keyword;
      }
      this.getProjectMediaRequirementsList();
    },
    //媒体需求列表
    getProjectMediaRequirementsList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        projectId: this.projectId,
        status: 1,
        keyword: this.keyword,
        stageId:this.currentStageid
      };
      API.getProjectMediaRequirementsList(params).then((res) => {
        if (res.key == 1000) {
          this.medialist = res.result;
        }
      });
    },
    handleInfoUpdate(updatedInfo) {
      if (updatedInfo) {
        let params = updatedInfo;
        API.editManageProject(params).then((res) => {
          if (res.key == 1000) {
            this.$message.success(res.message);
          }
        });
      }
    },
    

    uploaddialog() {
      this.dialogVisible = true;
    },
    checkedFile(obj) {
      let that = this;
      let url = `/checkorder/manager/pc/user/importExcel?token=${this.$store.state.token}`;
      this.projectFile = obj.file;
      const formData = new FormData();
      formData.append("file", obj.file); //file 和 后端字段要保持一致
      formData.append("token", this.$store.state.token);
      //formData.append("fileType", this.form.fileType);
      formData.append("projectId", this.projectId);
      const config = {
        headers: {
          "Access-Control-Allow-Origin": "*",
          token: this.$store.state.token,
        },
        timeout: 1000 * 60 * 10, //这里2分钟内的配置是生效的，超过了就不行。。
      };
      const loading = this.$loading({
        lock: true,
        text: "导入中，若数据量过大，则时间较长，在此期间请勿操作，请等待......",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      return axios
        .post(url, formData, config)
        .then((rs) => {
          if (rs.status === 200) {
            let data = rs.data;
            if (data.key === 1000) {
              that.$message.success({
                showClose: true,
                message: "上传成功",
                duration: 1500,
              });
              that.goodList = [];
              let goodList = data.result.list;

              if (this.form.fileType == 1) {
                goodList.forEach((item) => {
                  item.totalPrice = (item.goodNum * item.goodPrice).toFixed(2);
                });
              } else if (this.form.fileType == 2) {
                goodList.forEach((item) => {
                  item.totalPrice = (item.num * item.price).toFixed(2);
                });
              } else if (this.form.fileType == 3) {
                goodList.forEach((item) => {
                  item.totalPrice = (item.num * item.price).toFixed(2);
                });
              }
              that.goodList = goodList;
            } else {
              that.$message({
                type: "warning",
                message: rs.data.message,
              });
            }
          } else {
            that.$message({
              type: "warning",
              message: rs,
            });
          }
          loading.close();
        })
        .catch((rs) => {
          loading.close();
          this.$message({
            type: "error",
            message: rs,
          });
        });
    },
    handleSave() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          this.$message({
            type: "warning",
            message: "请检查上面输入项",
          });
          return;
        }
        if (!this.goodList || this.goodList.length < 1) {
          this.$message({
            type: "warning",
            message: "请上传文件",
          });
          return;
        }
        this.$bus.$emit("show-loading", true);
        const params = {
          projectId: this.projectId,
         // fileType: this.form.fileType,
          goods: JSON.stringify(this.goodList),
        };
       
        if (!params.projectId) {
          APIOrder.sendOrderUpdate(params, "application/json").then((res) => {
            if (res.key === 1000) {
              this.goodList = [];
            }
            this.$bus.$emit("show-loading", false);
          });
        } else {
          APIOrder.sendOrder(params, "application/json").then((res) => {
            if (res.key === 1000) {
              //this.submitProjectFile()
              this.$message.success(res.message);
              this.$emit('get-stage');
              this.dialogVisible = false;
            }
            this.$bus.$emit("show-loading", false);
          });
        }
      });
    },
    submitProjectFile() {
      const params = {
        file: this.projectFile,
        projectId: this.projectId,
        fileType: 5122,
      };
      APIProjectFile.doAddProjectFile(params).then((res) => {
        console.log("res====", res);
      });
    },
    uploadFileLoading(e) {
      this.uploadLoading = true;
    },

        getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      let sumColums = [];
      if (this.form.fileType == 1) {
        sumColums = ["goodNum", "goodPrice", "totalPrice"];
      } else if (this.form.fileType == 2) {
        sumColums = ["num", "price", "totalPrice"];
      } else if (this.form.fileType == 3) {
        sumColums = ["num", "price", "totalPrice"];
      }
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          !values.every((value) => isNaN(value)) &&
          sumColums.includes(column.property)
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += " 元";
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },

  },
  created() {
    console.log('创建中组件')
    let projectId = this.$ls.get("projectId");
    if (projectId) {
      this.projectId = projectId;
      this.getProjectManageMsg();
      this.getProjectMediaRequirementsList();
    }
    this.getSysLabelList();
  },
};
</script>

<style>
.upbtn {
  display: flex;
  justify-content: center;
}
</style>
